package com.mt.mtyx.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.mtyx.activity.mapper.CouponInfoMapper;
import com.mt.mtyx.activity.mapper.CouponRangeMapper;
import com.mt.mtyx.activity.service.CouponInfoService;
import com.mt.mtyx.common.exception.BusinessException;
import com.mt.mtyx.common.utils.Helper;
import com.mt.mtyx.dto.activity.CouponRuleDto;
import com.mt.mtyx.entity.activity.CouponInfo;
import com.mt.mtyx.entity.activity.CouponRange;
import com.mt.mtyx.entity.product.Category;
import com.mt.mtyx.entity.product.SkuInfo;
import com.mt.mtyx.enums.CouponRangeType;
import com.mt.mtyx.product.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WMT
 * @Date 2023/7/24 15:56
 */
@Service
public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements CouponInfoService {

    @Autowired
    private CouponRangeMapper couponRangeMapper;

    @Autowired
    private ProductFeignClient productFeignClient;


    @Override
    public IPage<CouponInfo> selectAll(Page<CouponInfo> couponInfoPage) {
        Page<CouponInfo> page = baseMapper.selectPage(couponInfoPage, null);
        if (page != null) {
            List<CouponInfo> records = page.getRecords();
            if (!CollectionUtils.isEmpty(records)) {
                records.stream().forEach(data -> {
                    data.setCouponTypeString(data.getCouponType().getComment());
                    CouponRangeType rangeType = data.getRangeType();
                    if (rangeType != null) {
                        data.setRangeTypeString(rangeType.getComment());
                    }
                });
            }
        }
        return page;
    }

    @Override
    public boolean existsByName(String couponInfoName) {
        return baseMapper.exists(new LambdaQueryWrapper<CouponInfo>().eq(CouponInfo::getCouponName, couponInfoName));
    }

    @Override
    public int insert(CouponInfo couponInfo) {
        Helper.setBaseProperties(couponInfo, LocalDateTime.now());
        return baseMapper.insert(couponInfo);
    }

    @Override
    public int delete(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int batchDelete(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int update(CouponInfo couponInfo) {
        couponInfo.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(couponInfo);
    }

    @Override
    public Map<String, Object> getCouponRuleList(Long couponId, CouponInfo couponInfo) {
        Map<String, Object> map = new HashMap<>(2);

        // 2.根据优惠券id,查询优惠券范围表的rangeId
        List<CouponRange> couponRangeList = couponRangeMapper.selectList(
                new LambdaQueryWrapper<CouponRange>().eq(CouponRange::getCouponId, couponId)
        );

        if (CollectionUtils.isEmpty(couponRangeList)) {
            return map;
        }

        // 获取所有rangeId
        List<Long> rangeIds = couponRangeList.stream()
                .map(CouponRange::getRangeId)
                .collect(Collectors.toList());

        // 3.封装不同类型的数据并返回
        if (!CollectionUtils.isEmpty(rangeIds)) {
            // 范围类型 为商品 rangeId == skuId
            if (couponInfo.getRangeType() == CouponRangeType.SKU) {
                List<SkuInfo> skuInfoList = productFeignClient.getSkuInfoListByIds(rangeIds);
                map.put("skuInfoList", skuInfoList);
                // 范围类型 为分类 rangeId == categoryId
            } else if (couponInfo.getRangeType() == CouponRangeType.CATEGORY) {
                List<Category> categoryList = productFeignClient.getCategoryListByIds(rangeIds);
                map.put("categoryList", categoryList);
            }
        }
        return map;
    }

    @Override
    public int saveCouponRule(CouponRuleDto dto) {
        int result = 0;
        // 1.删除之前的优惠券规则
        couponRangeMapper.delete(
                new LambdaQueryWrapper<CouponRange>().eq(CouponRange::getCouponId, dto.getCouponId())
        );

        // 2.更新优惠券信息
        CouponInfo couponInfo = baseMapper.selectById(dto.getCouponId());
        couponInfo.setRangeType(dto.getRangeType());
        couponInfo.setConditionAmount(dto.getConditionAmount());
        couponInfo.setAmount(dto.getAmount());
        couponInfo.setConditionAmount(dto.getConditionAmount());
        couponInfo.setRangeDesc(dto.getRangeDesc());
        couponInfo.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(couponInfo);

        // 3.添加新的有优惠券规则
        List<CouponRange> couponRangeList = dto.getCouponRangeList();
        if (!CollectionUtils.isEmpty(couponRangeList)) {
            List<CouponRange> couponRanges = couponRangeList.stream()
                    .peek(data -> {
                        data.setCouponId(dto.getCouponId());
                    })
                    .collect(Collectors.toList());
            result = couponRangeMapper.batchSave(couponRanges);
        }
        return result;
    }

    @Override
    public List<CouponInfo> findCouponByKeyword(String keyword) {
        return baseMapper.selectList(
                new LambdaQueryWrapper<CouponInfo>().like(CouponInfo::getCouponName, keyword)
        );
    }
}
